package com.dkhseep.bigevent.service.impl;

import com.dkhseep.bigevent.mapper.UserMapper;
import com.dkhseep.bigevent.pojo.User;
import com.dkhseep.bigevent.service.UserService;
import com.dkhseep.bigevent.util.JwtUtil;
import com.dkhseep.bigevent.util.Md5Util;
import com.dkhseep.bigevent.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能:
 * 作者:Dksheep
 * 日期:2024/9/2920:32
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired private UserMapper userMapper;
    @Autowired private StringRedisTemplate stringRedisTemplate;

    @Override
    public User findUserByUsername(String username) {
        User user = userMapper.findUserByUsername(username);
        return user;
    }

    @Override
    public void register(String username, String password) {
        String mdpassword = Md5Util.getMD5String(password);
        userMapper.adduser(username,password);
    }

    @Override
    public void updateuser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateuser(user);
    }

    @Override
    public void updateUserAvatar(String avatarUrl) {
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");//取出id
        userMapper.updateUserAvatar(avatarUrl,id);
    }

    @Override
    public boolean JudgeOldPassword(String old_pwd) {
        Map<String,Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        String password = this.findUserByUsername(username).getPassword();
        return Md5Util.getMD5String(old_pwd).equals(password);
    }

    @Override
    public boolean JudgeNew_RePassowrd(String new_pwd, String re_pwd) {
        return new_pwd.equals(re_pwd);
    }

    @Override
    public void updateUserPassword(String new_pwd) {
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        userMapper.updateUserPassword(Md5Util.getMD5String(new_pwd),id);
    }

    @Override
    public void deletetoken() {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        Map<String,Object>claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        operations.getOperations().delete(username);
    }

    @Override
    public String gettoken(User user) {
        Map<String,Object>clamis = new HashMap<>();
        clamis.put("id",user.getId());
        clamis.put("username",user.getUsername());
        String token = JwtUtil.genToken(clamis);
        return token;
    }
}
